package com.example.springmvc.controller;

// @Commpoent
// @Repositry
// @Service
// @Controler

import com.example.springmvc.exception.MyException;
import com.example.springmvc.pojo.Item;
import com.example.springmvc.service.IItemService;
import com.example.springmvc.service.impl.ItemServiceImpl;
import com.example.springmvc.vo.QueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
//下面所有的接口前面都要加上item
@RequestMapping("/item")
public class ItemController
{

    /*//请求映射地址注解
    @RequestMapping("/itemList.action")
    public ModelAndView itemList()
    {
        List<Item> list = new ArrayList<>();
        list.add(new Item(1, "1华为 荣耀8", 2399, new Date(), "质量好！1"));
        list.add(new Item(2, "2华为 荣耀8", 2399, new Date(), "质量好！2"));
        list.add(new Item(3, "3华为 荣耀8", 2399, new Date(), "质量好！3"));
        list.add(new Item(4, "4华为 荣耀8", 2399, new Date(), "质量好！4"));
        list.add(new Item(5, "5华为 荣耀8", 2399, new Date(), "质量好！5"));
        list.add(new Item(6, "6华为 荣耀8", 2399, new Date(), "质量好！6"));

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",list);
        //modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
        modelAndView.setViewName("itemList");

        return modelAndView;
    }*/

    @Autowired
    private IItemService itemService;

    //请求映射地址注解
    @RequestMapping("/itemList2.action")
    public ModelAndView itemList2()
    {
        List<Item> list = itemService.queryItemList();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",list);
//        modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
        modelAndView.setViewName("itemList");

        return modelAndView;
    }

    /*@RequestMapping("/itemEdit.action")
    public ModelAndView itemEdit(HttpServletRequest req){
        String idStr=req.getParameter("id");
        int id=Integer.parseInt(idStr);
        // 根据id查询商品数据
        Item item = this.itemService.queryItemByID(id);

        // 把结果传递给页面
        ModelAndView modelAndView = new ModelAndView();
        // 把商品数据放在模型中
        modelAndView.addObject("item", item);
        // 设置逻辑视图
        modelAndView.setViewName("itemEdit");

        return modelAndView;
    }*/

    /*@RequestMapping("/itemEdit.action")
    public String itemEdit(HttpServletRequest req, Model model){
        String idStr=req.getParameter("id");
        int id=Integer.valueOf(idStr);
        // 根据id查询商品数据
        Item item = this.itemService.queryItemByID(id);

//        // 把结果传递给页面
//        ModelAndView modelAndView = new ModelAndView();
//        // 把商品数据放在模型中
//        modelAndView.addObject("item", item);
//        // 设置逻辑视图
//        modelAndView.setViewName("itemEdit");

        model.addAttribute("item",item);

        return "editItem";
    }*/

    /*@RequestMapping("/itemEdit.action")
    public String itemEdit(Integer id, Model model){
    //String idStr=req.getParameter("id");
    //int id=Integer.valueOf(idStr);
        // 根据id查询商品数据
        Item item = this.itemService.queryItemByID(id);

        //// 把结果传递给页面
        //ModelAndView modelAndView = new ModelAndView();
        //// 把商品数据放在模型中
        //modelAndView.addObject("item", item);
        //// 设置逻辑视图
        //modelAndView.setViewName("itemEdit");

        model.addAttribute("item",item);

        return "editItem";
    }*/

    @RequestMapping("/itemEdit.action")
    /*使用@RequestParam常用于处理简单类型的绑定。
    value：参数名字，即入参的请求参数名字，如value=“itemId”表示请求的参数	   区中的名字为itemId的参数的值将传入
    required：是否必须，默认是true，表示请求中一定要有相应的参数，否则将报错
    TTP Status 400 - Required Integer parameter 'XXXX' is not present
    defaultValue：默认值，表示如果请求中没有同名参数时的默认值*/
    public String itemEdit(@RequestParam(value = "id", required = true, defaultValue = "1") Integer id, Model model){
        //String idStr=req.getParameter("id");
        //int id=Integer.valueOf(idStr);
        // 根据id查询商品数据
        System.out.println(id);
        Item item = this.itemService.queryItemByID(id);

        //// 把结果传递给页面
        //ModelAndView modelAndView = new ModelAndView();
        //// 把商品数据放在模型中
        //modelAndView.addObject("item", item);
        //// 设置逻辑视图
        //modelAndView.setViewName("itemEdit");

        model.addAttribute("item",item);

        return "editItem";
    }

    @RequestMapping("/updateItem.action")
    public String updateItem(Item item){
        itemService.updateItemById(item);
        return "success";
    }

    @RequestMapping("/queryItem.action")
    public String queryItem(QueryVo queryVo){
        int id=queryVo.getItem().getId();
        String name=queryVo.getItem().getName();

        System.out.println(id);
        System.out.println(name);
        System.out.println(Arrays.toString(queryVo.getIds()));
        System.out.println(queryVo.getItemList());
        for (Item i: queryVo.getItemList()) {
            System.out.println(i);
        }
        return "success";
    }

    @RequestMapping("/itemList3.action")
    public ModelAndView itemList3()
    {
        List<Item> list = itemService.queryItemList();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",list);
//        modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
        modelAndView.setViewName("itemList3");

        return modelAndView;
    }

    @RequestMapping(value = {"/itemList4.action","itemListAll.action"})
    public ModelAndView itemList4()
    {
        List<Item> list = itemService.queryItemList();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",list);
//        modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
        modelAndView.setViewName("itemList");

        return modelAndView;
    }

    @RequestMapping(value = "/itemList5.action",method= RequestMethod.POST)
    public ModelAndView itemList5()
    {
        List<Item> list = itemService.queryItemList();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",list);
//        modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
        modelAndView.setViewName("itemList");

        return modelAndView;
    }

    @RequestMapping("itemList6.action")
    public void itemList6(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request,response);
        response.getWriter().println("ok");
    }

    /*@RequestMapping("updateItem2.action")
    public String updateItemById(Item item) {
        this.itemService.updateItemById(item);
        return "redirect:/item/itemEdit.action?itemId="+item.getId();
    }*/

    //测试出现异常
    @RequestMapping(value = "/itemList7.action")
    public ModelAndView itemList7() throws MyException {
        int r=(int)(Math.random()*4);
        if(r==0){
            int x=r/0;
        }else  if(r==1){
            throw new MyException("自定义异常出现了~");
        }else if(r==2){
            int[] arr={1,2,3};
            System.out.println(arr[3]);
        }

        List<Item> list = itemService.queryItemList();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",list);
        modelAndView.setViewName("itemList");

        return modelAndView;
    }

    @RequestMapping("updateItem2.action")
    public String updateItemById(Item item, MultipartFile pictureFile) throws IOException {
        // 图片上传
        // 设置图片名称，不能重复，可以使用uuid
        String picName = UUID.randomUUID().toString();
        // 获取文件名
        String oriName = pictureFile.getOriginalFilename();
        // 获取图片后缀
        String extName = oriName.substring(oriName.lastIndexOf("."));
        // 开始上传
        pictureFile.transferTo(new File("D:/pic/" + picName + extName));
        // 设置图片名到商品中
        item.setPic(picName + extName);
        // ---------------------------------------------
        // 更新商品
        this.itemService.updateItemById(item);
        return "redirect:/item/itemList2.action?";//itemEdit.action?itemId="+item.getId()
    }

//    @RequestMapping("testJson.action")//接收的数据类型
//    @ResponseBody//返回的数据类型
//    public Item testJson(@RequestBody Item item){
//        System.out.println("接收到了"+item.getId()+item.getName());
//        return item;
//    }


    /**
     * 测试json的交互
     * @param item
     * @return
     * 上面注解有@RequestMapping("/item")
     */
    @RequestMapping("testJson.action")
    @ResponseBody
    public Item testJson(@RequestBody Item item)
    {
        System.out.println("item:"+item);
        return item;
    }


    // http://127.0.0.1:8080/item/1
    // @PathVariable() 路径获取参数
    /**
     * 使用RESTful风格开发接口，实现根据id查询商品
     *
     * @param id
     * @return
     */
    @GetMapping("item/{id}")
    @ResponseBody
    public Item queryItemById(@PathVariable() Integer id) {
        Item item = this.itemService.queryItemByID(id);
        return item;
    }

    @GetMapping("item/")
    @ResponseBody
    public List<Item> queryItems()
    {
        List<Item> items = this.itemService.queryItemList();
        return items;
    }

    @PostMapping("item/")
    @ResponseBody
    public Item addItem(@RequestBody Item item)
    {
        this.itemService.addItem(item);
        return item;
    }

    @PutMapping("item/")
    @ResponseBody
    public Item updateItem3(@RequestBody Item item)
    {
        this.itemService.updateItemById(item);
        return item;
    }

    @DeleteMapping("item/{id}")
    @ResponseBody
    public String deleteItemById(@PathVariable() Integer id)
    {
        this.itemService.deleteById(id);
        return "ok";
    }

}
